﻿using System;
using System.Collections.Generic;
using System.Linq;
using MiP.Common;
using MiP.ShellArgs;
using MiP.XmlCmd.Shell.Commands;

namespace MiP.XmlCmd.Shell.Args
{
    public class ArgsParser : IArgsParser
    {
        private readonly HelpCommand _helpCommand;
        private readonly ILogger _logger;
        private readonly IParser _parser;

        public ArgsParser(HelpCommand helpCommand, ILogger logger)
        {
            if (helpCommand == null)
                throw new ArgumentNullException("helpCommand");
            if (logger == null)
                throw new ArgumentNullException("logger");

            _helpCommand = helpCommand;
            _logger = logger;

            _parser = new Parser()
                .AutoWire<Arguments>(
                    c => c.WithOption(pc=>pc.Variables.CurrentValue())
                          .Do(pc => pc.Container.VariableSources.Add(new VariableSource(pc.Value, false)))
                          .WithOption(pc=>pc.VariableFiles.CurrentValue())
                          .Do(pc => pc.Container.VariableSources.Add(new VariableSource(pc.Value, true)))
                );
        }

        public Arguments Parse(IEnumerable<string> args)
        {
            try
            {
                return _parser.Parse(args.ToArray()).Result<Arguments>();
            }
            catch (ParsingException ex)
            {
                _logger.Error(ex.Message + Environment.NewLine);

                _logger.Error("USAGE: " + _parser.GetShortHelp() + Environment.NewLine);

                _helpCommand.Execute();
                return null;
            }
        }
    }
}